<template>
  <div>
    <el-form label-width="100px">
      <el-form-item label="SKU名称">
        <el-input
          placeholder="Sku name"
          v-model="paramsSkuData.skuName"
        ></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input
          v-model="paramsSkuData.price"
          placeholder="价格(元)"
          type="number"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量(g)">
        <el-input
          v-model="paramsSkuData.weight"
          placeholder="重量(g)"
          type="number"
        ></el-input>
      </el-form-item>
      <el-form-item label="SKU描述">
        <el-input
          v-model="paramsSkuData.skuDesc"
          placeholder="SKU描述"
          type="textarea"
        ></el-input>
      </el-form-item>
      <!-- attr 属性展示 -->
      <el-form-item label="平台属性">
        <el-form label-width="100px" inline>
          <el-form-item
            style="margin: 5px 0"
            v-for="spuItem in allSpuAttr"
            :key="spuItem.id"
            :label="spuItem.attrName"
          >
            <el-select v-model="spuItem.attrIdAndValueId">
              <el-option
                v-for="item in spuItem.attrValueList"
                :key="item.id"
                :label="item.valueName"
                :value="`${spuItem.id}:${item.id}`"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form label-width="100px" inline>
          <el-form-item
            style="margin: 10px 0"
            v-for="spuValue in curSpuValue"
            :key="spuValue.id"
            :label="spuValue.saleAttrName"
          >
            <el-select v-model="spuValue.saleIdAndSaleValueId">
              <el-option
                v-for="item in spuValue.spuSaleAttrValueList"
                :key="item.id"
                :value="`${spuValue.id}:${item.id}`"
                :label="item.saleAttrValueName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-table ref="tableRef" border :data="curImage">
          <el-table-column
            type="selection"
            width="80px"
            align="center"
            :data="curImage"
          ></el-table-column>
          <el-table-column label="图片">
            <template #default="{ row }">
              <el-image
                :src="row.imgUrl"
                style="width: 100px; height: 100px"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                :disabled="true"
                v-if="row.id === defaultButtonId"
                @click="setDefaultImage(row)"
                type="primary"
                size="small"
              >
                默认图片
              </el-button>
              <el-button
                v-else
                @click="setDefaultImage(row)"
                size="small"
                icon="Plus"
              >
                设置默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="saveSku">保存</el-button>
        <el-button size="small" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { reqAllImage, reqSaleAttrHasList } from '@/api/product/spu'
import { addSku } from '@/api/product/spu'
import type { SkuData } from '@/api/product/spu/type'
import { getAttrData } from '@/api/product/attr'
import { ElMessage } from 'element-plus'
import useCategoryStore from '@/store/modules/category'
const categoryStore = useCategoryStore()

const $emit = defineEmits(['changeShowType'])
const saveSku = async () => {
  paramsSkuData.skuAttrValueList = allSpuAttr.value.reduce(
    (prev: any, next: any) => {
      if (next.attrIdAndValueId) {
        const [attrId, valueId] = next.attrIdAndValueId.split(':')
        prev.push({
          attrId,
          valueId,
        })
      }
      return prev
    },
    [],
  )
  paramsSkuData.skuSaleAttrValueList = curSpuValue.value.reduce(
    (prev: any, next: any) => {
      if (next.saleIdAndSaleValueId) {
        const [saleAttrId, saleAttrValueId] =
          next.saleIdAndSaleValueId.split(':')
        prev.push({
          saleAttrId,
          saleAttrValueId,
        })
      }
      return prev
    },
    [],
  )
  const res = await addSku(paramsSkuData)
  cancel()
  res.code === 200
    ? ElMessage.success('添加Sku成功')
    : ElMessage.error('操作失误,请重新尝试')
}
const tableRef = ref()
const defaultButtonId = ref('')
// 点击设置默认图片
const setDefaultImage = (row: any) => {
  console.log(row)
  defaultButtonId.value = row.id
  tableRef.value?.clearSelection()
  tableRef.value?.toggleRowSelection(row, true)
  paramsSkuData.skuDefaultImg = row.imgUrl
}
// 点击取消
const cancel = () => {
  Object.assign(paramsSkuData, {
    //父组件传递过来的数据
    category3Id: '', //三级分类的ID
    spuId: '', //已有的SPU的ID
    tmId: '', //SPU品牌的ID

    //v-model收集
    skuName: '', //sku名字
    price: '', //sku价格
    weight: '', //sku重量
    skuDesc: '', //sku的描述

    skuAttrValueList: [
      //平台属性的收集
    ],
    skuSaleAttrValueList: [
      //销售属性
    ],
    skuDefaultImg: '', //sku图片地址
  })
  $emit('changeShowType', {
    flag: 0,
    params: 'update',
  })
}

const curImage = ref<any>([])
const curSpuValue = ref<any>([])
const allSpuAttr = ref<any>([])
const paramsSkuData = reactive<SkuData>({
  //父组件传递过来的数据
  category3Id: '', //三级分类的ID
  spuId: '', //已有的SPU的ID
  tmId: '', //SPU品牌的ID

  //v-model收集
  skuName: '', //sku名字
  price: '', //sku价格
  weight: '', //sku重量
  skuDesc: '', //sku的描述

  skuAttrValueList: [
    //平台属性的收集
  ],
  skuSaleAttrValueList: [
    //销售属性
  ],
  skuDefaultImg: '', //sku图片地址
})

const initData = async (row: any) => {
  curImage.value.value = []
  curSpuValue.value = []
  allSpuAttr.value = []
  paramsSkuData.category3Id = row.category3Id
  paramsSkuData.spuId = row.id
  paramsSkuData.tmId = row.tmId
  // const resImages = await reqAllImage(row.id)
  // const resSpu = await reqSaleAttrHasList(row.id)
  // const resAttr = await getAttrData(c1Id, c2Id, c3Id)
  const { c3Id, c2Id, c1Id } = categoryStore
  const promises = [
    reqAllImage(row.id),
    reqSaleAttrHasList(row.id),
    getAttrData(c1Id, c2Id, c3Id),
  ]
  const [resImages, resSpu, resAttr] = await Promise.all(promises)
  if (resImages.code === 200) {
    curImage.value = resImages.data
  }
  if (resImages.code === 200) {
    curSpuValue.value = resSpu.data
  }
  if (resImages.code === 200) {
    allSpuAttr.value = resAttr.data
  }
}
defineExpose({
  initData,
})
</script>

<script lang="ts">
export default {
  name: 'Sku',
}
</script>
<style lang="scss" scoped></style>
